import { downloadFile, getBase64WithBlob, getUrlWithBlob } from '@/utils/file'
import { watermark } from '@/utils/watermark'
import * as ExcelJS from 'exceljs'
import { ref, unref } from 'vue'

export const useExcelWatermark = () => {
  const resBlob = ref()

  /**
   * @description excel文件添加水印
   * @param bytes 原始文件的arrarybuffer文件流
   * @param waterText 水印文本，可选
   */
  const excelWatermark = async (bytes: ArrayBuffer, waterText = 'mm system watermark') => {
    // 加载原始文件的unit64Arrary文件流
    const workbook = new ExcelJS.Workbook()
    await workbook.xlsx.load(bytes)
    // 获取水印图片的base64
    const blob: Blob = (await watermark(document.createElement('canvas'), waterText)) as Blob
    const base64: string = await getBase64WithBlob(blob)
    // 添加水印图片
    const imageId = await workbook.addImage({ base64, extension: 'png' })
    workbook.worksheets.forEach((sheet) => {
      sheet.addBackgroundImage(imageId)
    })
    // 获取处理后文件的unit64Arrary文件流
    const resBuffer = await workbook.xlsx.writeBuffer()
    resBlob.value = new Blob([resBuffer], { type: 'application/octet-stream' })
  }

  const saveExcel = (fileName: string) => {
    const url = getUrlWithBlob(unref(resBlob))
    downloadFile(url, fileName)
  }

  return {
    excelWatermark,
    saveExcel,
  }
}
